/**
 * File: ContigIndexProcessor.java
 * Created by: mhaimel
 * Created on: Apr 20, 2010
 * CVS:  $Id: ContigIndexProcessor.java 1.0 Apr 20, 2010 3:47:50 PM mhaimel Exp $
 */
package uk.ac.ebi.curtain.processor.load;

import java.io.File;
import java.io.IOException;

import uk.ac.ebi.curtain.processor.AbstractProcessor;
import uk.ac.ebi.curtain.service.IdentifierStore;
import uk.ac.ebi.curtain.storage.sequence.SequenceBox;
import uk.ac.ebi.curtain.storage.sequence.fast.FastSequenceBoxWriter;
import uk.ac.ebi.curtain.utils.CurtainUncheckedException;
import uk.ac.ebi.curtain.utils.data.DataEntry;
import uk.ac.ebi.curtain.utils.data.MetaData;
import uk.ac.ebi.curtain.utils.data.ReadType;
import uk.ac.ebi.curtain.utils.file.EntryMapper;
import uk.ac.ebi.curtain.utils.file.EntryMapperBean;
import uk.ac.ebi.curtain.utils.file.FileInfo;
import uk.ac.ebi.curtain.utils.io.impl.FileIO;

/**
 * @author mhaimel
 *
 */
public class ContigIndexProcessor extends AbstractProcessor<DataEntry<File>, DataEntry<File>> {

	@Override
	protected DataEntry<File> buildReturnObject() {
		return getInput();
	}

	@Override
	public void process() {

		DataEntry<File> entry = getInput();
		MetaData meta = entry.getMetaData();
		
		
		if(!meta.getReadType().equals(ReadType.Contig)){
			throw new IllegalArgumentException("Only Contig files should be used with this class!!!" + entry);
		}
		FileInfo tmp = new FileInfo(entry.getEntries()[0], meta.getFileType(), meta.getReadType());
		Integer cat = getContext().getArguments().getCategory(tmp);
		if(cat < 0){
			cat = Integer.MAX_VALUE+cat;
		}
		final Integer category = cat; 
		final FastSequenceBoxWriter writer = new FastSequenceBoxWriter(getContext().currentFiles().getSequenceBoxMapping(meta.getReadType(), category,true),true);
		final IdentifierStore<String, Integer> ctgIdx = getContext().getContigIndex();
		try{
			writer.open();
			for(File f : entry.getEntries()){
				FileInfo fi = new FileInfo(f, meta.getFileType(), meta.getReadType());
				meta.getFileType().getParser().parse(fi, new EntryMapper() {
					@Override
					public void mapEntry(EntryMapperBean bean) {
						Integer id = ctgIdx.getOrAddIdentifier(bean.getId());
						try {
							writer.write(id.longValue(), new SequenceBox(bean.getId(), bean.getSequence()));
						} catch (IOException e) {
							throw new CurtainUncheckedException(e);
						}
					}
				});
			}
		} catch (IOException e) {
			throw new CurtainUncheckedException(e);
		} finally{
			FileIO.closeQuietly(writer);
		}
	}
	
}
